<!DOCTYPE html>
<html lang="en" data-bs-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Docker Container Monitor</title>
    <link href="./bootstrap/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="./bootstrap/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --success-color: #27ae60;
            --warning-color: #f39c12;
            --danger-color: #e74c3c;
            --info-color: #1abc9c;
            --dark-color: #2c3e50;
            --light-color: #ecf0f1;
        }
        
        [data-bs-theme="dark"] {
            --primary-color: #5dade2;
            --secondary-color: #34495e;
            --success-color: #2ecc71;
            --warning-color: #f5b041;
            --danger-color: #ec7063;
            --info-color: #48c9b0;
            --dark-color: #34495e;
            --light-color: #f8f9fa;
        }
        
        .status-running { color: var(--success-color); }
        .status-stopped { color: var(--danger-color); }
        .status-paused { color: var(--warning-color); }
        
        .container-card {
            transition: all 0.3s ease;
            border: none;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
        }
        
        .container-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 20px rgba(0,0,0,0.15);
        }
        
        .port-badge, .mount-badge {
            font-size: 0.75rem;
            padding: 0.4em 0.6em;
            border-radius: 6px;
            margin-right: 0.25rem;
            margin-bottom: 0.25rem;
        }
        
        .btn-custom {
            border-radius: 8px;
            padding: 0.375rem 0.75rem;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        
        .btn-custom:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .btn-custom:active {
            transform: translateY(0);
        }
        
        .theme-toggle {
            background: none;
            border: none;
            font-size: 1.2rem;
            cursor: pointer;
            color: var(--dark-color);
        }
        
        [data-bs-theme="dark"] .theme-toggle {
            color: var(--light-color);
        }
        
        .header-gradient {
            background: linear-gradient(135deg, var(--primary-color), var(--info-color));
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .stats-card {
            border-radius: 12px;
            overflow: hidden;
            transition: transform 0.3s ease;
        }
        
        .stats-card:hover {
            transform: scale(1.02);
        }
        
        .modal-content {
            border-radius: 15px;
            border: none;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        
        .modal-header {
            background: linear-gradient(135deg, var(--primary-color), var(--info-color));
            color: white;
            border-radius: 15px 15px 0 0 !important;
        }
        
        .badge-custom {
            border-radius: 20px;
            padding: 0.5em 1em;
            font-weight: 500;
        }
        
        .table th {
            border-top: none;
            font-weight: 600;
        }
        
        .table-hover tbody tr:hover {
            background-color: rgba(0,0,0,0.03);
        }
        
        [data-bs-theme="dark"] .table-hover tbody tr:hover {
            background-color: rgba(255,255,255,0.05);
        }
        
        .loading-spinner {
            width: 3rem;
            height: 3rem;
        }
        
        .container-image {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 10px;
            background: linear-gradient(135deg, var(--primary-color), var(--info-color));
            color: white;
            font-size: 1.2rem;
        }
    </style>
</head>
<body>
    <div class="container-fluid py-4">
        <div class="row">
            <div class="col-12">
                <div class="header-gradient d-flex justify-content-between align-items-center">
                    <h1 class="mb-0">
                        <i class="bi bi-boxes"></i> Docker Container Monitor
                    </h1>
                    <div class="d-flex align-items-center">
                        <button id="themeToggle" class="theme-toggle me-3">
                            <i class="bi bi-moon"></i>
                        </button>
                        <button id="refreshBtn" class="btn btn-light">
                            <i class="bi bi-arrow-clockwise"></i> Refresh
                        </button>
                    </div>
                </div>
                
                <!-- Stats Cards -->
                <div class="row mb-4" id="stats-container">
                    <div class="col-md-3 col-6 mb-3">
                        <div class="card stats-card border-0 shadow-sm">
                            <div class="card-body text-center">
                                <h5 class="card-title text-muted">Total</h5>
                                <h2 class="mb-0" id="total-containers">0</h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 col-6 mb-3">
                        <div class="card stats-card border-0 shadow-sm">
                            <div class="card-body text-center">
                                <h5 class="card-title text-success">Running</h5>
                                <h2 class="mb-0" id="running-containers">0</h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 col-6 mb-3">
                        <div class="card stats-card border-0 shadow-sm">
                            <div class="card-body text-center">
                                <h5 class="card-title text-danger">Stopped</h5>
                                <h2 class="mb-0" id="stopped-containers">0</h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 col-6 mb-3">
                        <div class="card stats-card border-0 shadow-sm">
                            <div class="card-body text-center">
                                <h5 class="card-title text-warning">Paused</h5>
                                <h2 class="mb-0" id="paused-containers">0</h2>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div id="containers-container" class="row">
                    <!-- Containers will be loaded here -->
                    <div class="text-center py-5">
                        <div class="spinner-border loading-spinner" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Container Detail Modal -->
    <div class="modal fade" id="containerModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content border-0">
                <div class="modal-header border-0">
                    <h5 class="modal-title" id="containerModalLabel">
                        <i class="bi bi-info-circle me-2"></i>Container Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="container-detail-content">
                        <!-- Container details will be loaded here -->
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-lg me-1"></i>Close
                    </button>
                </div>
            </div>
        </div>
    </div>
    <script src="./bootstrap/bootstrap.bundle.min.js"></script>
    <script>
        // Global variable to store containers data
        let containersData = [];
        
        // Theme toggle functionality
        const themeToggle = document.getElementById('themeToggle');
        const htmlElement = document.documentElement;
        
        // Check for saved theme preference or respect OS preference
        const savedTheme = localStorage.getItem('theme');
        const osTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
        const currentTheme = savedTheme || osTheme;
        
        htmlElement.setAttribute('data-bs-theme', currentTheme);
        themeToggle.innerHTML = currentTheme === 'dark' ? '<i class="bi bi-sun"></i>' : '<i class="bi bi-moon"></i>';
        
        themeToggle.addEventListener('click', () => {
            const currentTheme = htmlElement.getAttribute('data-bs-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            
            htmlElement.setAttribute('data-bs-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            themeToggle.innerHTML = newTheme === 'dark' ? '<i class="bi bi-sun"></i>' : '<i class="bi bi-moon"></i>';
        });
        
        // Function to update stats
        function updateStats(containers) {
            const total = containers.length;
            const running = containers.filter(c => c.state === 'running').length;
            const stopped = containers.filter(c => c.state === 'exited' || c.state === 'stopped').length;
            const paused = containers.filter(c => c.state === 'paused').length;
            
            document.getElementById('total-containers').textContent = total;
            document.getElementById('running-containers').textContent = running;
            document.getElementById('stopped-containers').textContent = stopped;
            document.getElementById('paused-containers').textContent = paused;
        }

        // Function to fetch containers
        async function fetchContainers() {
            try {
                const response = await fetch('/api/v1/containers');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const containers = await response.json();
                containersData = containers;
                renderContainers(containers);
            } catch (error) {
                console.error('Error fetching containers:', error);
                document.getElementById('containers-container').innerHTML = 
                    `<div class="alert alert-danger">Error loading containers: ${error.message}</div>`;
            }
        }

        // Function to render containers
        function renderContainers(containers) {
            const container = document.getElementById('containers-container');
            
            if (containers.length === 0) {
                container.innerHTML = '<div class="alert alert-info">No containers found</div>';
                return;
            }
            
            // Update stats
            updateStats(containers);
            
            let html = '';
            containers.forEach(container => {
                html += `
                <div class="col-12 col-md-6 col-lg-4 mb-4">
                    <div class="card container-card h-100 border-0 shadow-sm">
                        <div class="card-body d-flex flex-column">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <div class="d-flex align-items-center">
                                    <div class="container-image me-3">
                                        <i class="bi bi-box"></i>
                                    </div>
                                    <div>
                                        <h5 class="card-title mb-1">${container.name}</h5>
                                        <span class="badge bg-secondary">${container.id.substring(0, 12)}</span>
                                    </div>
                                </div>
                                <span class="badge bg-${container.state === 'running' ? 'success' : container.state === 'stopped' ? 'danger' : 'warning'} badge-custom">
                                    ${container.state.charAt(0).toUpperCase() + container.state.slice(1)}
                                </span>
                            </div>
                            
                            <div class="mb-3">
                                <p class="card-text mb-1">
                                    <small class="text-muted">
                                        <i class="bi bi-card-image me-1"></i> ${container.image}
                                    </small>
                                </p>
                                <p class="card-text mb-1">
                                    <small class="text-muted">
                                        <i class="bi bi-calendar me-1"></i> ${new Date(container.created * 1000).toLocaleDateString()}
                                    </small>
                                </p>
                                ${container.pid > 0 ? `
                                <p class="card-text mb-1">
                                    <small class="text-muted">
                                        <i class="bi bi-cpu me-1"></i> PID: ${container.pid}
                                    </small>
                                </p>` : ''}
                            </div>
                            
                            ${container.ports && container.ports.length > 0 ? `
                            <div class="mb-3">
                                <p class="card-text mb-1">
                                    <small class="text-muted">Ports:</small>
                                </p>
                                <div>
                                    ${container.ports.slice(0, 3).map(port => 
                                        `<span class="badge bg-primary port-badge">${port.PrivatePort}/${port.Type} → ${port.PublicPort || 'N/A'}</span>`
                                    ).join('')}
                                    ${container.ports.length > 3 ? `<span class="badge bg-secondary port-badge">+${container.ports.length - 3} more</span>` : ''}
                                </div>
                            </div>` : ''}
                            
                            ${container.mounts && container.mounts.length > 0 ? `
                            <div class="mb-3">
                                <p class="card-text mb-1">
                                    <small class="text-muted">Mounts:</small>
                                </p>
                                <div>
                                    ${container.mounts.slice(0, 2).map(mount => 
                                        `<span class="badge bg-info mount-badge" title="${mount.Source} → ${mount.Destination}">${mount.Type}: ${mount.Destination.split('/').pop()}</span>`
                                    ).join('')}
                                    ${container.mounts.length > 2 ? `<span class="badge bg-secondary mount-badge">+${container.mounts.length - 2} more</span>` : ''}
                                </div>
                            </div>` : ''}
                            
                            <div class="mt-auto d-flex flex-wrap gap-2">
                                <button class="btn btn-sm btn-outline-primary btn-custom view-details-btn" data-id="${container.id}">
                                    <i class="bi bi-eye"></i> Details
                                </button>
                                ${container.state === 'running' ? `
                                <button class="btn btn-sm btn-outline-warning btn-custom stop-btn" data-id="${container.id}">
                                    <i class="bi bi-stop-circle"></i> Stop
                                </button>
                                <button class="btn btn-sm btn-outline-success btn-custom restart-btn" data-id="${container.id}">
                                    <i class="bi bi-arrow-repeat"></i> Restart
                                </button>
                                ` : `
                                <button class="btn btn-sm btn-outline-success btn-custom start-btn" data-id="${container.id}">
                                    <i class="bi bi-play-circle"></i> Start
                                </button>
                                `}
                                <button class="btn btn-sm btn-outline-danger btn-custom remove-btn" data-id="${container.id}">
                                    <i class="bi bi-trash"></i> Remove
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                `;
            });
            
            container.innerHTML = html;
            
            // Add fade-in animation
            const cards = container.querySelectorAll('.col-12');
            cards.forEach((card, index) => {
                card.style.opacity = '0';
                card.style.transform = 'translateY(20px)';
                setTimeout(() => {
                    card.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
                    card.style.opacity = '1';
                    card.style.transform = 'translateY(0)';
                }, 100 * index);
            });
            
            // Add event listeners
            document.querySelectorAll('.stop-btn').forEach(btn => {
                btn.addEventListener('click', () => stopContainer(btn.dataset.id));
            });
            
            document.querySelectorAll('.start-btn').forEach(btn => {
                btn.addEventListener('click', () => startContainer(btn.dataset.id));
            });
            
            document.querySelectorAll('.restart-btn').forEach(btn => {
                btn.addEventListener('click', () => restartContainer(btn.dataset.id));
            });
            
            document.querySelectorAll('.remove-btn').forEach(btn => {
                btn.addEventListener('click', () => removeContainer(btn.dataset.id));
            });
            
            document.querySelectorAll('.view-details-btn').forEach(btn => {
                btn.addEventListener('click', () => viewContainerDetails(btn.dataset.id));
            });
        }

        // Function to show loading state for buttons
        function showButtonLoading(button) {
            button.disabled = true;
            const originalHTML = button.innerHTML;
            button.innerHTML = '<span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>Loading...';
            return originalHTML;
        }
        
        // Function to hide loading state for buttons
        function hideButtonLoading(button, originalHTML) {
            button.disabled = false;
            button.innerHTML = originalHTML;
        }

        // Function to stop a container
        async function stopContainer(id) {
            if (!confirm('Are you sure you want to stop this container?')) return;
            
            const button = document.querySelector(`.stop-btn[data-id="${id}"]`);
            const originalHTML = showButtonLoading(button);
            
            try {
                const response = await fetch(`/api/v1/containers/${id}/stop`, {
                    method: 'POST'
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // Show success feedback
                button.innerHTML = '<i class="bi bi-check-circle me-1"></i>Stopped';
                button.classList.remove('btn-outline-warning');
                button.classList.add('btn-success');
                
                // Refresh the list after a short delay
                setTimeout(() => {
                    fetchContainers();
                }, 1000);
            } catch (error) {
                console.error('Error stopping container:', error);
                alert(`Error stopping container: ${error.message}`);
                hideButtonLoading(button, originalHTML);
            }
        }

        // Function to start a container
        async function startContainer(id) {
            const button = document.querySelector(`.start-btn[data-id="${id}"]`);
            const originalHTML = showButtonLoading(button);
            
            try {
                const response = await fetch(`/api/v1/containers/${id}/start`, {
                    method: 'POST'
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // Show success feedback
                button.innerHTML = '<i class="bi bi-check-circle me-1"></i>Started';
                button.classList.remove('btn-outline-success');
                button.classList.add('btn-success');
                
                // Refresh the list after a short delay
                setTimeout(() => {
                    fetchContainers();
                }, 1000);
            } catch (error) {
                console.error('Error starting container:', error);
                alert(`Error starting container: ${error.message}`);
                hideButtonLoading(button, originalHTML);
            }
        }

        // Function to restart a container
        async function restartContainer(id) {
            if (!confirm('Are you sure you want to restart this container?')) return;
            
            const button = document.querySelector(`.restart-btn[data-id="${id}"]`);
            const originalHTML = showButtonLoading(button);
            
            try {
                const response = await fetch(`/api/v1/containers/${id}/restart`, {
                    method: 'POST'
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // Show success feedback
                button.innerHTML = '<i class="bi bi-check-circle me-1"></i>Restarted';
                button.classList.remove('btn-outline-success');
                button.classList.add('btn-success');
                
                // Refresh the list after a short delay
                setTimeout(() => {
                    fetchContainers();
                }, 1000);
            } catch (error) {
                console.error('Error restarting container:', error);
                alert(`Error restarting container: ${error.message}`);
                hideButtonLoading(button, originalHTML);
            }
        }

        // Function to remove a container
        async function removeContainer(id) {
            if (!confirm('Are you sure you want to remove this container? This action cannot be undone.')) return;
            
            const button = document.querySelector(`.remove-btn[data-id="${id}"]`);
            const originalHTML = showButtonLoading(button);
            
            try {
                const response = await fetch(`/api/v1/containers/${id}`, {
                    method: 'DELETE'
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // Show success feedback
                button.innerHTML = '<i class="bi bi-check-circle me-1"></i>Removed';
                button.classList.remove('btn-outline-danger');
                button.classList.add('btn-success');
                
                // Refresh the list after a short delay
                setTimeout(() => {
                    fetchContainers();
                }, 1000);
            } catch (error) {
                console.error('Error removing container:', error);
                alert(`Error removing container: ${error.message}`);
                hideButtonLoading(button, originalHTML);
            }
        }

        // Function to view container details
        async function viewContainerDetails(id) {
            try {
                const response = await fetch(`/api/v1/containers/${id}`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const container = await response.json();
                
                const modalContent = document.getElementById('container-detail-content');
                modalContent.innerHTML = `
                    <div class="row">
                        <div class="col-md-6">
                            <div class="card border-0 shadow-sm mb-4">
                                <div class="card-header bg-primary text-white">
                                    <h5 class="mb-0">
                                        <i class="bi bi-info-circle me-2"></i>Container Information
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <table class="table table-borderless mb-0">
                                        <tr><td><strong>ID</strong></td><td class="text-break">${container.id}</td></tr>
                                        <tr><td><strong>Name</strong></td><td>${container.name}</td></tr>
                                        <tr><td><strong>Image</strong></td><td>${container.image}</td></tr>
                                        <tr><td><strong>Status</strong></td><td>
                                            <span class="badge bg-${container.state === 'running' ? 'success' : container.state === 'stopped' ? 'danger' : 'warning'}">
                                                ${container.status}
                                            </span>
                                        </td></tr>
                                        <tr><td><strong>State</strong></td><td>
                                            <span class="badge bg-${container.state === 'running' ? 'success' : container.state === 'stopped' ? 'danger' : 'warning'}">
                                                ${container.state}
                                            </span>
                                        </td></tr>
                                        <tr><td><strong>Created</strong></td><td>${new Date(container.created * 1000).toLocaleString()}</td></tr>
                                        ${container.pid > 0 ? `<tr><td><strong>PID</strong></td><td>${container.pid}</td></tr>` : ''}
                                        <tr><td><strong>Command</strong></td><td class="text-break">${container.command}</td></tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card border-0 shadow-sm mb-4">
                                <div class="card-header bg-info text-white">
                                    <h5 class="mb-0">
                                        <i class="bi bi-diagram-3 me-2"></i>Ports
                                    </h5>
                                </div>
                                <div class="card-body">
                                    ${container.ports && container.ports.length > 0 ? `
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Private Port</th>
                                                    <th>Type</th>
                                                    <th>Public Port</th>
                                                    <th>IP</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                ${container.ports.map(port => `
                                                    <tr>
                                                        <td>${port.PrivatePort}</td>
                                                        <td>${port.Type}</td>
                                                        <td>${port.PublicPort || 'N/A'}</td>
                                                        <td>${port.IP || 'N/A'}</td>
                                                    </tr>
                                                `).join('')}
                                            </tbody>
                                        </table>
                                    </div>
                                    ` : '<p class="mb-0">No ports exposed</p>'}
                                </div>
                            </div>
                            
                            <div class="card border-0 shadow-sm">
                                <div class="card-header bg-success text-white">
                                    <h5 class="mb-0">
                                        <i class="bi bi-folder me-2"></i>Mounts
                                    </h5>
                                </div>
                                <div class="card-body">
                                    ${container.mounts && container.mounts.length > 0 ? `
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Type</th>
                                                    <th>Source</th>
                                                    <th>Destination</th>
                                                    <th>Mode</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                ${container.mounts.map(mount => `
                                                    <tr>
                                                        <td>${mount.Type}</td>
                                                        <td class="text-break">${mount.Source}</td>
                                                        <td class="text-break">${mount.Destination}</td>
                                                        <td>${mount.Mode}</td>
                                                    </tr>
                                                `).join('')}
                                            </tbody>
                                        </table>
                                    </div>
                                    ` : '<p class="mb-0">No mounts configured</p>'}
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                // Show the modal
                const modal = new bootstrap.Modal(document.getElementById('containerModal'));
                modal.show();
            } catch (error) {
                console.error('Error fetching container details:', error);
                alert(`Error fetching container details: ${error.message}`);
            }
        }

        // Initialize the page
        document.addEventListener('DOMContentLoaded', function() {
            // Fetch containers on page load
            fetchContainers();
            
            // Add refresh button event listener
            document.getElementById('refreshBtn').addEventListener('click', fetchContainers);
        });
    </script>
</body>
</html>